<template>
  <div>
    <el-card class="box-card">
      <el-form
        :model="AddNewsForm"
        :rules="rules"
        ref="AddNewsForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="新闻标题" prop="Title">
          <el-input
            v-model="AddNewsForm.Title"
            placeholder="请输入新闻标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="新闻分类" prop="NewsCategoryId">
          <!-- 新闻分类应该用级联 -->
          <!-- <el-select
            v-model="AddNewsForm.NewsCategoryId"
            placeholder="请选择新闻分类"
          >
            <el-option
              v-for="(item, index) in newsCategories"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
          <el-cascader
            placeholder="请选择，支持搜索功能"
            style="width: 400px"
            v-model="AddNewsForm.PidArr"
            :options="options"
            filterable
            :props="{ checkStrictly: true, expandTrigger: 'hover' }"
          >
          </el-cascader>

        </el-form-item>
        
        <el-form-item label="新闻简介" required prop="Describe">
          <el-input
            v-model="AddNewsForm.Describe"
            placeholder="请选择新闻简介"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="新闻封面" prop="TitlePic">
          <el-col :span="12">
            <!-- <img :src="baseImgURL+AddNewsForm.TitlePic" v-show="oldImgShow" style="width:100%" /> -->
            <upload
              @returnUrl="handleReturnUrl"
              actionURL="NewsTitlePic"
            ></upload>
          </el-col>
        </el-form-item>
        <el-form-item label="正文" prop="Content">
          <!-- <mavon-editor
            v-model="AddNewsForm.Content"
            ref="md"
            style="min-height: 600px"
          /> -->
          <mavon-editor
            v-model="AddNewsForm.Content"
            :ishljs="true"
            :codeStyle="code_style"
            ref="md"
            @imgAdd="$imgAdd"
            @imgDel="$imgDel"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('AddNewsForm')"
            >立即创建</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入mavonEditor组件 及 组件样式
// import { mavonEditor } from "mavon-editor";
// import "mavon-editor/dist/css/index.css";
import {getNewsCategoryTree} from "@/api/api"

import upload from "@/components/Upload/Upload.vue";
// import News from "@/api/News.js";
// const news=new News();

// 引入api接口
// import { uploadNewsContentPic,BaseApiUrl } from "@/api/api";
import axios from "@/api/api";
import {siteUrl} from "@/api/constTools"

export default {
  data() {
    return {
      // baseImgURL:'http://121.196.246.105:4000/#/News/TitlePic/',
      // oldImgShow:false,
      img_file: [],//mavon-editor接收图片使用

      options: [],
      newsCategories: [],
      AddNewsForm: {
        Title: "",
        NewsCategoryId: "",
        Describe: "",
        TitlePic: "",
        Content: "",
        Weight: 0,
        PidArr:[]
      },
      rules: {
        Title: [
          { required: true, message: "请输入新闻标题", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        NewsCategoryId: [
          { required: true, message: "请选择新闻分类", trigger: "blur" },
        ],
        Describe: [
          { required: true, message: "请输入新闻简介", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        TitlePic: [
          { required: true, message: "请上传新闻封面", trigger: "blur" },
        ],
        Content: [
          { required: true, message: "请输入新闻内容", trigger: "blur" },
          {
            min: 1,
            max: 5000,
            message: "长度在 1 到 1000 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // Mavon-editor
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("image", $file);
      this.img_file[pos] = $file;
      axios({
        url: "/images/Upload/Pic",
        method: "post",
        data: formdata,
        headers: { "Content-Type": "multipart/form-data" },
      }).then((res) => {
        let _res = res.data;
        // console.log(_res);
        // console.log(BaseApiUrl);
        let fullPath=siteUrl+_res.response
        console.log(fullPath);
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        this.$refs.md.$img2Url(pos, fullPath);
      });
    },
    $imgDel(pos) {
      delete this.img_file[pos];
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // console.log(this.AddNewsForm);
          const response = await news.CreateNewsInLogin(
            this.AddNewsForm,
            this.$store.state.token
          );
          // console.log(response);
          if (response.code === 200) {
            // 操作成功
            this.$message.success("操作成功");
            window.setInterval(() => {
              this.$router.push("/User/NewsManage/NewsInShow");
            }, 200);
          } else {
            // 操作失败
            this.$message.error("服务器错误，操作失败！");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 上传成功后：由子组件传值返回Url
    handleReturnUrl(data) {
      this.AddNewsForm.TitlePic = data;
    },
  },
  components: {
    // mavonEditor,
    upload,
  },
  async mounted() {
    // 绑定新闻分类数据
    // this.newsCategories = this.$store.state.newsCategories;
    this.options = [];
      this.addFormVisible = true;
      this.addLoading = true;
      // this.addForm = {
      //   // ncID: 0,
      //   // ncName: "",
      //   // ncParentID: 0,
      //   // ncWeight: 0,
      //   // CreateBy: "",
      //   // CreateId: "",
      //   // PidArr: [],
      //   // Name: "",
      //   // Code: "",
      //   // OrderSort: 0,
      //   // Description: "",
      //   // Enabled: true,
      //   // Icon: "",
      //   // IsButton: false,
      //   // IsHide: false,
      //   // IskeepAlive: false
        
      // };

      let para = { pid: 0 };
      //   getPermissionTree(para).then(res => {
      //     ++this.isResouceShow;
      //     this.options.push(res.data.response);
      //      this.addLoading = false;

      //   });
      getNewsCategoryTree(para).then((res) => {
        // this.users = res.data.response;
        ++this.isResouceShow;
        // console.log(res.data.response);
        this.options.push(res.data.response);
        // console.log(this.options);
        this.addLoading = false;
      });
  },
};
</script>